Python Program to Reverse a Number Using Recursion in 4 different ways

 
Python program to reverse a number using recursion with step by step explanation

Hi friends welcome back to DailyCodeHub.

When you start learning programming, most problems are first solved using loops because loops are easy to understand and easy to write. but in interviews, sometimes the same problem is asked using recursion.

That is where many beginners get confused.
One such common problem is reversing a number using recursion.
At first recursion looks difficult because the function keeps calling itself again and again. but once you understand how each call works step by step it becomes very simple and interesting.

This problem is important because it helps you understand how recursion works in real programs. it also improves your problem-solving skills.

In this post i will explain everything in a very simple way so that you can understand it clearly and explain it confidently in interviews.

Let us get started.

Before we start, let us understand the basics :

Reversing a number means changing the order of its digits.
For example :
Input: 123
Output: 321
This means we take digits from the right side and rebuild the number from the left side.

In recursion, instead of using loops we solve the problem by calling the same function again and again until a condition is met.

Question :

Write a Python program to reverse a number using recursion.

Method 1 : Using Recursion | Level : Intermediate | Best for : Interviews

This is the most important method to understand recursion. 

Code :

# Author: P.Prabhas

# Reverse a number using recursion (simple version)
def reverse_number(num, rev):
    # Step 1: Stop when number becomes 0
    if num == 0:
        return rev
    # Step 2: Take last digit
    last_digit = num % 10
    # Step 3: Add digit to reversed number
    rev = rev * 10 + last_digit
    # Step 4: Recursive call
    return reverse_number(num // 10, rev)

# Step 5: Take input from user
num = int(input("Enter a number: "))

# Step 6: Call function
result = reverse_number(num, 0)

# Step 7: Print result
print("Reversed number is:", result)

Output:

Enter a number: 123
Reversed number: 321

How it works :

First we define a function called reverse_number. this function takes two values. one is the number and the other is the reversed value which starts from 0.

Inside the function, we first check whether the number is 0. If it is 0, we return the reversed value. this is the base condition that stops the recursion.

If the number is not 0, we take the last digit using num% 10. this gives us one digit at a time from the right side.

Then we add that digit to the reversed value. before adding we multiply the current reversed value by 10 so that the digit shifts to the left and makes space for the new digit.

After that we call the same function again with the remaining number using num // 10.

This process continues again and again until the number becomes 0.

Finally the reversed number is returned.

This works because each function call processes one digit and passes the remaining digits to the next call.

Method 2 : Using Recursion with Negative Numbers | Level : Important | Best for : Real programs

This method handles both positive and negative numbers.

Code :


# Author: P.Prabhas

# Function to reverse number using recursion
def reverse_number(num, rev):
    # Base condition
    if num == 0:
        return rev
    # Extract last digit
    digit = num % 10
    # Build reversed number
    rev = rev * 10 + digit
    # Recursive call
    return reverse_number(num // 10, rev)

# Take input
num = int(input("Enter a number: "))

# Store sign
sign = 1
if num < 0:
    sign = -1
    num = abs(num)

# Reverse number
result = reverse_number(num, 0)

# Apply sign and print result
print("Reversed number:", sign * result)

Output:

Enter a number: -123
Reversed number: -321

How it works :

First we take a number from the user. then we check whether the number is negative.

If the number is negative, we store the sign separately and convert the number into a positive value using abs().

Then we apply the recursion logic to reverse the number.

After reversing, we multiply the result with the stored sign.

This ensures correct result for both positive and negative numbers.

Method 3 : Using Helper Function | Level : Intermediate | Best for : Clean structure

Code :

# Author: P.Prabhas

# Helper function for recursion
def helper(num, rev):
    # Base condition
    if num == 0:
        return rev
    # Extract last digit
    digit = num % 10
    # Build reversed number
    rev = rev * 10 + digit
    # Recursive call
    return helper(num // 10, rev)

# Main function
def reverse_number(num):
    # Call helper function
    return helper(num, 0)

# Take input
num = int(input("Enter a number: "))

# Print result
print("Reversed number:", reverse_number(num))

Output:

Enter a number: 123
Reversed number: 321

How it works :

In this method we use two functions. one function is used to start the process and the other function performs the actual reversing.

The helper function works exactly like the previous recursion method. it processes one digit at a time and calls itself again.

The main function simply calls the helper function with the initial value.

This method makes the code easier to reuse and understand in bigger programs.

Methods summary table :

Method Technique Level Best For
Recursion Function calls Intermediate Interviews
Recursion + Sign Real case Important Practical
Helper Function Clean code Intermediate Reusability

Key points to remember :
  • Recursion means function calling itself
  • Base condition is very important
  • % 10 gives last digit
  • // 10 removes last digit
  • Each call processes one digit
You can also read this:
Frequently asked questions :

Q. What is recursion?
A) A function calling itself

Q. Which method is best?
A) Basic recursion method

Q.Is recursion important?
A) Yes

Q. Why use recursion?
A) To solve problems step by step

Conclusion :

Reversing a number using recursion looks difficult at first time, but once you understand how each
function call works it becomes very simple.

This problem is very useful for understanding recursion and improving your problem-solving skills.
Practice this program step by step and try to trace how the function calls itself.

That's all for today friends.

Keepcoding,keep learning.
DailyCodeHub

No comments:

Post a Comment